import structlog
from config.setting import BASE_DIR, CONFIG
from litestar.logging.config import LoggingConfig, StructLoggingConfig
from litestar.middleware.logging import LoggingMiddlewareConfig
from litestar.plugins.structlog import StructlogConfig
from structlog.dev import RichTracebackFormatter

# class CustomRotatingFileHandler(TimedRotatingFileHandler):
#     def __init__(
#         self,
#         filename: str | PathLike[str],
#         when: str = ...,
#         interval: int = ...,
#         backupCount: int = ...,
#         encoding: str | None = ...,
#         delay: bool = ...,
#         utc: bool = ...,
#         atTime: Any | None = ...,
#         errors: str | None = ...,
#     ) -> None:
#         super().__init__(
#             filename,
#             when,
#             interval,
#             backupCount,
#             encoding,
#             delay,
#             utc,
#             atTime,
#             errors,
#         )


# # 日志配置
# logging_config = LoggingConfig(
#     # root={"level": logging.getLevelName(logging.INFO), "handlers": ["console"]},
#     formatters={
#         "standard": {
#             "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
#             "datefmt": "%Y-%m-%d %H:%M:%S",
#         },
#     },
# )

# # 日志实例
# logger = logging_config.configure()()

structlog_config = StructlogConfig(
    enable_middleware_logging=True,
    structlog_logging_config=StructLoggingConfig(
        processors=[
            structlog.contextvars.merge_contextvars,
            structlog.processors.add_log_level,
            # structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S.%f", utc=False),
            structlog.processors.TimeStamper(fmt="iso", utc=False),
            structlog.dev.ConsoleRenderer(
                colors=True,
                exception_formatter=RichTracebackFormatter(
                    max_frames=1, show_locals=False, width=80
                ),
            ),
        ],
        log_exceptions="always",
        traceback_line_limit=6,
        standard_lib_logging_config=LoggingConfig(
            formatters={
                "standard": {
                    "format": "%(levelname)s - %(asctime)s.%(msecs)03d - %(name)s - %(module)s - %(message)s",  # noqa: E501
                    "datefmt": CONFIG["log"]["datefmt"],
                },
            },
            handlers={
                "file_handler": {
                    "class": "logging.handlers.TimedRotatingFileHandler",
                    "level": CONFIG["log"]["level"],
                    "filename": BASE_DIR / "log" / CONFIG["log"]["filename"],
                    "when": CONFIG["log"]["when"],
                    "interval": CONFIG["log"]["interval"],
                    "backupCount": CONFIG["log"]["backup_count"],
                    "formatter": "standard",
                }
            },
            root={
                "level": "INFO",
                "handlers": ["queue_listener"],
            },
            loggers={
                "uvicorn": {
                    "propagate": False,
                    "level": "INFO",
                    "handlers": ["queue_listener", "file_handler"],
                },
                "uvicorn.access": {
                    "propagate": False,
                    "level": "INFO",
                    "handlers": ["queue_listener", "file_handler"],
                },
                # "uvicorn.error": {
                #     "propagate": False,
                #     "level": "INFO",
                #     "handlers": ["queue_listener", "file_handler"],
                # },
                # "granian.access": {
                #     "propagate": False,
                #     "level": "INFO",
                #     "handlers": ["queue_listener"],
                # },
                # "granian.error": {
                #     "propagate": False,
                #     "level": "INFO",
                #     "handlers": ["queue_listener"],
                # },
                # "saq": {
                #     "propagate": False,
                #     "level": "INFO",
                #     "handlers": ["queue_listener"],
                # },
                "sqlalchemy.engine": {
                    "propagate": False,
                    "level": "INFO",
                    "handlers": ["queue_listener", "file_handler"],
                },
                "sqlalchemy.pool": {
                    "propagate": False,
                    "level": "INFO",
                    "handlers": ["queue_listener", "file_handler"],
                },
            },
        ),
    ),
    middleware_logging_config=LoggingMiddlewareConfig(
        request_log_fields=["method", "path", "path_params", "query"],
        response_log_fields=["status_code"],
    ),
)
